package com.macro.mall.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.macro.mall.mapper.OmsOrderItemMapper;
import com.macro.mall.mapper.OmsOrderMapper;
import com.macro.mall.model.OmsOrder;
import com.macro.mall.model.OmsOrderItem;
import com.macro.mall.model.OmsOrderItemExample;
import com.macro.mall.portal.service.JdyService;
import com.macro.mall.portal.util.HttpKit;
import com.macro.mall.portal.util.JsonDateValueProcessor;
import com.macro.mall.portal.vo.JdyEntriesVO;
import com.macro.mall.portal.vo.JdyOrderVO;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class JdyServiceImpl implements JdyService {
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private Environment env;
    @Autowired
    private OmsOrderMapper omsOrderMapper;

    @Override
    public Map<String, Object> getJdyProductById(String productId) {
        String s = HttpKit.get("https://api.kingdee.com/auth/user/access_token?client_id=208016&client_secret=3b066b4de7fcae08143860abb0103dec&username=18566163838&password=qq66194790");
        Map<String,Object> ress = JSON.parseObject(s, Map.class);
        Map<String,Object> token = (Map<String, Object>) ress.get("data");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> productNumberMap= new HashMap<>();
        productNumberMap.put("productNumber",productId);
        map.put("filter",productNumberMap);
        String data = JSONObject.fromObject(map).toString();
        String res1 = HttpKit.post("https://api.kingdee.com/jdyscm/product/list?access_token="+token.get("access_token")+"&dbId="+env.getProperty("jdy.dbId"),data,headers);
        Map<String,Object> map1 = JSON.parseObject(res1, Map.class);
        if ((int)map1.get("code")==0){
            return map1;
        }
        return null;
    }
    @Override
    public List<JdyOrderVO> salesSlip(OmsOrder omsOrder) {
        String s = HttpKit.get("https://api.kingdee.com/auth/user/access_token?client_id=208016&client_secret=3b066b4de7fcae08143860abb0103dec&username=18566163838&password=qq66194790");
        Map<String,Object> ress = JSON.parseObject(s, Map.class);
        Map<String,Object> token = (Map<String, Object>) ress.get("data");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Map<String,Object> map = new HashMap<>();
        JdyOrderVO jdyOrderVO = new JdyOrderVO();
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd" );
        OmsOrderItemExample example = new OmsOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(example);
        jdyOrderVO.setReceivedAmt(omsOrder.getPayAmount());
        jdyOrderVO.setDate(sdf.format(omsOrder.getPaymentTime()));
        jdyOrderVO.setCustomerNumber(env.getProperty("jdy.customerNumber"));
        jdyOrderVO.setEmployeeNumber(env.getProperty("jdy.employeeNumber"));
        jdyOrderVO.setRemark(omsOrder.getNote());
        Map<String,Object> accounts = new HashMap<>();
        accounts.put("number",env.getProperty("jdy.accounts.number"));
        accounts.put("payment",omsOrder.getPayAmount());
        List<Map<String,Object>> accuntsList = new ArrayList<>();
        accuntsList.add(accounts);
        jdyOrderVO.setAccounts(accuntsList);
        List<JdyEntriesVO> entriesList = new ArrayList<>();
        for (OmsOrderItem orderItem: omsOrderItems){
            Map<String, Object> jdyProduct = getJdyProductById(orderItem.getProductSn());
            System.out.println("jdyProduct="+jdyProduct);
            if (CollUtil.isEmpty(jdyProduct)){
                System.out.println("---------------------------------");
                continue;
            }
            JdyEntriesVO jdyEntriesVO = new JdyEntriesVO();
            List<Map<String, Object>> items = (List<Map<String, Object>>) jdyProduct.get("items");
            List<Map<String, Object>> skus = (List<Map<String, Object>>) items.get(0).get("invSku");
            if (CollUtil.isNotEmpty(skus)){
               // Map<String, Object> sku= new HashMap<>();
                for (Map<String, Object> sk: skus){
                    if (sk.get("skuNumber").equals(orderItem.getProductSkuCode())){
                       // sku=sk;
                        jdyEntriesVO.setSkuCode(sk.get("skuNumber").toString());
                        continue;
                    };
                }
            }
            if ((int)items.get(0).get("isWarranty")==1){
                Map<String, Object>  warranty = warrantyList(orderItem.getProductSn());
                List<Map<String, Object>> warrantyitems=(List<Map<String, Object>>) warranty.get("items");
                jdyEntriesVO.setProdDate(warrantyitems.get(0).get("prodDate").toString());
                if (warrantyitems.get(0).containsKey("batch")){
                    jdyEntriesVO.setBatch(warrantyitems.get(0).get("batch").toString());
                }
            }
            jdyEntriesVO.setProductNumber(items.get(0).get("productNumber").toString());
            jdyEntriesVO.setLocation(env.getProperty("jdy.entries.location"));
            jdyEntriesVO.setUnit(items.get(0).get("unit").toString());
            jdyEntriesVO.setPrice(orderItem.getProductPrice().doubleValue());
            jdyEntriesVO.setQty(orderItem.getProductQuantity());
//            entries.put("productNumber",orderItem.getProductSkuCode());
//            entries.put("unit",items.get(0).get("unit").toString());
//            entries.put("price",orderItem.getProductPrice().doubleValue());
//            entries.put("location",env.getProperty("jdy.entries.location"));
//            entries.put("qty",orderItem.getProductQuantity());
//            entries.put("prodDate",new Date());
            entriesList.add(jdyEntriesVO);
        }
        if (CollUtil.isEmpty(entriesList)){
            System.out.println("entriesList"+entriesList);
            return null;
        }
        jdyOrderVO.setEntries(entriesList);
        List<JdyOrderVO> jdyOrderVOS = new ArrayList<>();
        jdyOrderVOS.add(jdyOrderVO);
        map.put("items",jdyOrderVOS);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        String data = JSONObject.fromObject(map,jsonConfig).toString();
        System.out.println(JSONObject.fromObject(map));
        System.out.println(data);
        String res1 = HttpKit.post("https://api.kingdee.com/jdyscm/delivery/add?access_token="+token.get("access_token")+"&dbId="+env.getProperty("jdy.dbId"),data,headers);
        Map<String,Object> map1 = JSON.parseObject(res1,Map.class);
        System.out.println("map1="+map1);
        return  JSON.parseArray(map1.get("items").toString(), JdyOrderVO.class) ;
    }

    @Override
    public Map<String, Object> purchaseAdd(Map<String, Object>  warranty,Map<String, Object> jdyProduct,OmsOrderItem orderItem,Map<String,Object> token) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyyMMdd" );
        List<Map<String, Object>> warrantyitems=(List<Map<String, Object>>) warranty.get("items");
        Map<String,Object> purchase = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        List<Map<String,Object>> entriesList = new ArrayList<>();
        List<Map<String,Object>> items = new ArrayList<>();
        List<Map<String, Object>> productItems = (List<Map<String, Object>>) jdyProduct.get("items");
        data.put("number","");
        data.put("date",sdf.format(new Date()));
        data.put("supplierNumber",env.getProperty("jdy.supplierNumber"));
        Map<String,Object> entries = new HashMap<>();
        entries.put("productNumber",productItems.get(0).get("productNumber"));
        entries.put("location",env.getProperty("jdy.entries.location"));
        entries.put("qty",orderItem.getProductQuantity());
        entries.put("price",productItems.get(0).get("elsPurPrice"));
        entries.put("unit",productItems.get(0).get("unit").toString());
        entries.put("prodDate",warrantyitems.get(0).get("prodDate"));
        entriesList.add(entries);
        data.put("entries",entriesList);
        items.add(data);
        purchase.put("items",items);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        String d = JSONObject.fromObject(purchase,jsonConfig).toString();
        System.out.println("购货"+d);
        String res= HttpKit.post("https://api.kingdee.com/jdyscm/purchase/add?access_token="+token.get("access_token")+"&dbId="+env.getProperty("jdy.dbId"),d,headers);
        return JSON.parseObject(res,Map.class);
    }

    @Override
    public Map<String, Object> warrantyList(String number) {
        String warranty= HttpKit.get("https://api.kingdee.com/jdyscm/warranty/list?access_token=1602145818fc3d3eccfbc43de7db0b6d&dbId=79849829157&number="+number);
        return JSON.parseObject(warranty, Map.class);
    }

}
